package cn.wolfcode.crm.shiro;

import cn.wolfcode.crm.util.JsonResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

@Component("crmFormAuthenticationFilter")

public class AjaxFormAuthenticationFilter extends FormAuthenticationFilter {

	protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
		JsonResult json = new JsonResult(true, "登录成功");
		response.setContentType("text/json;charset=UTF-8");
		response.getWriter().print(JSON.toJSONString(json));
		return false;
	}


	protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
		String msg = "";
		if (e instanceof UnknownAccountException) {
			msg = "账号错误!";
		} else if (e instanceof IncorrectCredentialsException) {
			msg = "密码错误!";
		} else {
			msg = "未知错误,请联系管理员!!";
		}
		e.printStackTrace();
		response.setContentType("text/json;charset=UTF-8");
		try {
			JsonResult result = new JsonResult(false, msg);
			response.getWriter().print(JSON.toJSONString(result));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return false;

	}




}